package com.js.nickcar.utils;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;


import com.js.nickcar.MyApplication;
import com.js.nickcar.R;

import me.nereo.multi_image_selector.MultiImageSelector;

/**
 * Created by 李宗源 on 2017/3/14.
 * <p>
 * <pre>
 * 使用
 *
 * @Override
 * protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 *     super.onActivityResult(requestCode, resultCode, data);
 *     switch (requestCode) {
 *          case REQUEST_STORAGE_READ_ACCESS_PERMISSION:
 *               //从设置界面返回，重新校验权限
 *               PickUtil.pickImage(fragment,false);
 *               break;
 *      }
 * }
 *
 * @Override
 * public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
 *      if (requestCode == REQUEST_SMS_PERMISSION) {
 *          if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 *              //请求权限成功,打开选取照片界面
 *          } else {
 *              TLog.d("zyzd", "TestActivity>>onRequestPermissionsResult--> 请求被拒绝");
 *              showToSettingPermission();
 *          }
 *          return;
 *      }
 *      super.onRequestPermissionsResult(requestCode, permissions, grantResults);
 * }
 * </pre>
 */

public class PickUtil {
    public static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 2102;
    public static final int REQUEST_CODE_IMAGE = 1101;
    public static final int REQUEST_CODE_SELECT_VIDEO = 1102;//选择视频
    public static final int REQUEST_CODE_RECORD_AUDIO = 1104;//录音权限

    /**
     * 打开选择图片界面
     */
    public static void pickImage(Activity activity, boolean isCrop) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                && ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE,
                    getString(R.string.mis_permission_rationale),
                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        } else {
            MultiImageSelector selector = MultiImageSelector.create();
            selector.single();
            selector.isCrop(isCrop);
            selector.showCamera(true);
            selector.start(activity, REQUEST_CODE_IMAGE);
        }
    }

    /**
     * 打开选择图片界面
     */
    public static void pickImage(Fragment fragment, boolean isCrop) {
        FragmentActivity activity = fragment.getActivity();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                && ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(fragment, Manifest.permission.READ_EXTERNAL_STORAGE,
                    getString(R.string.mis_permission_rationale),
                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        } else {
            MultiImageSelector selector = MultiImageSelector.create();
            selector.single();
            selector.isCrop(isCrop);
            selector.showCamera(true);
            selector.start(fragment, REQUEST_CODE_IMAGE);
        }
    }

//    public static void pickVideo(Fragment fragment) {
//        FragmentActivity activity = fragment.getActivity();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
//                && ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE)
//                != PackageManager.PERMISSION_GRANTED) {
//            requestPermission(fragment, Manifest.permission.READ_EXTERNAL_STORAGE,
//                    getString(R.string.mis_permission_rationale),
//                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
//        } else {
//            Intent intent = new Intent(activity, ImageGridActivity.class);
//            fragment.startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);
//        }
//    }

    /**
     * 请求权限
     *
     * @param activity
     * @param permission
     * @param rationale
     * @param requestCode
     */
    public static void requestPermission(final Activity activity, final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
            new AlertDialog.Builder(activity)
                    .setTitle(R.string.mis_permission_dialog_title)
                    .setMessage(rationale)
                    .setPositiveButton(R.string.mis_permission_dialog_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            openSettingActivity(activity, requestCode);
                        }
                    })
                    .setNegativeButton(R.string.mis_permission_dialog_cancel, null)
                    .create().show();
        } else {
            ActivityCompat.requestPermissions(activity, new String[]{permission}, requestCode);
        }
    }

    /**
     * @param fragment
     * @param permission
     * @param rationale
     * @param requestCode
     */
    public static void requestPermission(final Fragment fragment, final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(fragment.getActivity(), permission)) {
            new AlertDialog.Builder(fragment.getActivity())
                    .setTitle(R.string.mis_permission_dialog_title)
                    .setMessage(rationale)
                    .setPositiveButton(R.string.mis_permission_dialog_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            openSettingActivity(fragment, requestCode);
                        }
                    })
                    .setNegativeButton(R.string.mis_permission_dialog_cancel, null)
                    .create().show();
        } else {
            fragment.requestPermissions(new String[]{permission}, requestCode);
        }
    }

    /**
     * 打开设置界面让用户进行设置
     *
     * @param fragment
     * @param requestCode
     */
    public static void openSettingActivity(final Fragment fragment, int requestCode) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", fragment.getActivity().getPackageName(), null);
        intent.setData(uri);
        fragment.startActivityForResult(intent, requestCode);
    }

    /**
     * 打开设置界面让用户进行设置
     *
     * @param activity
     * @param requestCode
     */
    public static void openSettingActivity(final Activity activity, int requestCode) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
        intent.setData(uri);
        activity.startActivityForResult(intent, requestCode);
    }

    private static String getString(int resId) {
        return MyApplication.getContext().getString(resId);
    }
}
